/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.manuscripts.tools.cli.imageLinks;

import cz.mzk.kramerius.fedoraaccess.DatastreamId;
import cz.mzk.kramerius.fedoraaccess.FedoraConnector;
import java.util.logging.Level;
import java.util.logging.Logger;
import rukopisyimport.foxml.ImageIdentifier;
import rukopisyimport.foxml.images.ImageUrlBuilder;

/**
 *
 * @author Martin Řehánek <rehan at mzk.cz>
 */
public class PageUpdater {

    private static final Logger logger = Logger.getLogger(PageUpdater.class.getName());
    private final FedoraConnector con;
    private final ImageUrlBuilder builder;

    public PageUpdater(FedoraConnector con, ImageUrlBuilder builder) {
        this.con = con;
        this.builder = builder;
    }

    public void updatePage(String pagePid, ImageIdentifier imageId) throws Exception {
        //TODO: poresit pripadne chyby behem "transakce"
        logger.log(Level.INFO, "updating page {0}", pagePid);
        upateRelsExt(pagePid, imageId);
        String imgFullUrl = builder.buildImgFullUrl(imageId);
        updateImageDatastream(pagePid, DatastreamId.IMG_FULL, imgFullUrl);
        String imgThumbUrl = builder.buildImgThumbUrl(imageId);
        updateImageDatastream(pagePid, DatastreamId.IMG_THUMB, imgThumbUrl);
    }

    private void upateRelsExt(String pagePid, ImageIdentifier imageId) throws Exception {
        String tilesUrl = builder.buildTilesUrl(imageId);
        (new RelsExtTilesAdder(con, tilesUrl)).updateDatastream(pagePid);
        logger.log(Level.INFO, "tiles-url added to RELS-EXT");
    }

    private void updateImageDatastream(String pagePid, DatastreamId dsId, String imageUrl) {
        con.purgeDatastream(pagePid, dsId, dsId.toString() + " will be updated");
        logger.log(Level.INFO, "datastream {0} has been removed", dsId.toString());
        con.addExternallyReferencedDatastream(pagePid, dsId, imageUrl, "jpeg");
        logger.log(Level.INFO, "datastream {0} with externall reference has been added", dsId.toString());
    }
}
